"use client"

import { useState } from "react"
import { Play, Lock, LockOpen, ShieldAlert, AlertTriangle, CheckCircle } from "lucide-react"
import { mockUsers } from "@/mocks/admin-data"
import { User } from "@/types/admin"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import StatusBadge from "@/components/status-badge"

// Mock current user - 默认使用管理员权限
const initialUser = mockUsers.find(u => u.role.name === '管理员')!;

type ActionStatus = "done" | "not_done"

interface ActionableItem {
  status: ActionStatus;
}

interface LabelledActionableItem extends ActionableItem {
  label: string;
}

type Status = "energized" | "de-energized"

interface TrackState {
  id: string;
  name: string;
  status: Status;
  isolatorClosed: boolean;
  verificationPoint: ActionableItem;
  groundingRod: ActionableItem & { label?: string };
  patrolPoints: LabelledActionableItem[];
  platformNames: string[];
  gateAccess: "allowed" | "denied"
}

const initialTracks: TrackState[] = [
    { id: 'L-23', name: '23', status: 'energized', isolatorClosed: true, verificationPoint: { status: 'not_done' }, groundingRod: { status: 'done', label: '23股道接地杆' }, patrolPoints: [{ label: '23股道巡检点', status: 'done' }], platformNames: ['吹扫库车顶作业平台'], gateAccess: 'denied' },
    { id: 'L-22', name: '22', status: 'de-energized', isolatorClosed: false, verificationPoint: { status: 'not_done' }, groundingRod: { status: 'not_done', label: '22股道接地杆' }, patrolPoints: [{ label: '22股道巡检点', status: 'not_done' }], platformNames: ['月检库车顶作业平台'], gateAccess: 'denied' },
    { id: 'L-21', name: '21', status: 'energized', isolatorClosed: true, verificationPoint: { status: 'not_done' }, groundingRod: { status: 'not_done', label: '21股道接地杆' }, patrolPoints: [{ label: '21股道巡检点', status: 'not_done' }], platformNames: ['月检库车顶作业平台'], gateAccess: 'denied' },
    { id: 'L-20', name: '20', status: 'energized', isolatorClosed: true, verificationPoint: { status: 'not_done' }, groundingRod: { status: 'not_done', label: '20股道接地杆' }, patrolPoints: [{ label: '20股道巡检点', status: 'not_done' }], platformNames: ['月检库车顶作业平台'], gateAccess: 'denied' },
    { id: 'L-19', name: '19', status: 'energized', isolatorClosed: true, verificationPoint: { status: 'not_done' }, groundingRod: { status: 'not_done', label: '19股道接地杆' }, patrolPoints: [{ label: '19股道 (靠20) 巡检点', status: 'not_done' }, { label: '19股道 (靠墙) 巡检点', status: 'not_done' }], platformNames: ['静调库车顶作业平台', '静调库车顶作业平台'], gateAccess: 'denied' }
];

const StatusIndicator = ({ label, active, color }: { label: string; active: boolean; color: 'red' | 'green' }) => {
    const colorClass = { 
      red: 'bg-[#FF4D4F]', 
      green: 'bg-[#52C41A]'
    }[color];
    
    return (
        <div className="flex items-center space-x-2">
            <span className="text-sm text-foreground w-8 text-center">{label}</span>
            <div className={`w-4 h-2 rounded-sm ${active ? colorClass : 'bg-muted border border-border'}`} />
        </div>
    );
};

const IsolatorSwitch = ({ name, closed, onClick }: { name: string; closed: boolean; onClick: () => void }) => (
    <div className="flex flex-col items-center">
        <span className="text-sm text-foreground mb-1">{name}</span>
        <button 
          onClick={onClick} 
          className="w-12 h-8 bg-muted/50 border-2 border-border p-1 flex items-center justify-center rounded-md hover:bg-muted transition-colors"
        >
            <div className="w-full h-1 bg-muted relative">
                <div className={`absolute top-0 left-0 w-1/2 h-full bg-[#1677FF] transition-transform duration-300 ease-in-out`}
                     style={{ transform: closed ? 'rotate(0deg)' : 'rotate(-45deg)', transformOrigin: '0% 50%' }}/>
            </div>
        </button>
    </div>
);

const VerificationPoint = ({ status, onClick }: { status: ActionStatus; onClick: () => void }) => (
    <button onClick={onClick} className="flex flex-col items-center group">
        <div className="w-12 h-8 bg-muted/50 border-2 border-[#FF4D4F] p-1 flex items-center justify-center rounded-md hover:bg-muted transition-colors">
             <div className={`w-4 h-4 rounded-full border-2 border-[#FF4D4F] ${status === 'done' ? 'bg-[#FF4D4F]' : 'bg-transparent'}`}></div>
        </div>
        <span className="text-xs text-muted-foreground mt-1 whitespace-nowrap group-hover:text-foreground">验电桩</span>
    </button>
);

const GroundingRod = ({ label, status, onClick }: { label: string; status: ActionStatus; onClick: () => void }) => (
    <button onClick={onClick} className="flex flex-col items-center group">
        <div className="relative">
            <div className={`w-3 h-3 rounded-full ${status === 'done' ? 'bg-[#FF4D4F]' : 'bg-muted'}`}></div>
            <div className="absolute left-1/2 -translate-x-1/2 top-full w-px h-3 bg-border"></div>
        </div>
        <span className="text-xs text-muted-foreground mt-3 whitespace-nowrap group-hover:text-foreground">{label}</span>
    </button>
);

const PatrolPoint = ({ label, status, onClick }: { label: string; status: ActionStatus; onClick: () => void }) => (
    <button onClick={onClick} className="flex flex-col items-center group">
        <div className={`w-8 h-4 border rounded-sm ${status === 'done' ? 'bg-[#52C41A] border-[#52C41A]/50' : 'bg-muted border-border'}`}></div>
        <span className="text-xs text-muted-foreground mt-1 whitespace-nowrap group-hover:text-foreground">{label}</span>
    </button>
);

const TrackLine = () => ( <div className="w-full h-1 bg-[#1677FF]/70"></div> );

const TrackIdLabel = ({ id }: { id: string }) => (
    <div className="relative w-20 h-8 flex items-center justify-center">
        <div className="absolute w-full h-full bg-[#F0F5FF] transform -skew-x-12 rounded-sm"></div>
        <span className="relative text-[#1677FF] font-mono">{id}</span>
    </div>
);

const PlatformDisplay = ({ name, gateAccess, patrolPoints, onPatrolPointClick }: { name: string; gateAccess: "allowed" | "denied"; patrolPoints: LabelledActionableItem[]; onPatrolPointClick: (index: number) => void; }) => {
    const GateSymbol = () => (
        <div className="w-6 h-8 grid grid-cols-2 grid-rows-4 bg-background rounded-sm overflow-hidden">
            {[...Array(8)].map((_, i) => ( <div key={i} className={i % 2 === (Math.floor(i / 2) % 2) ? 'bg-[#FF4D4F]' : 'bg-background'}></div> ))}
        </div>
    );
    const GateAccessIcon = gateAccess === 'allowed' 
        ? <LockOpen className="w-5 h-5 text-[#52C41A]" /> 
        : <Lock className="w-5 h-5 text-[#FF4D4F]" />;

    return (
        <div className="w-11/12">
            <div className="relative flex items-center justify-center w-full bg-[#E6F7FF] border border-[#1677FF]/30 p-2 min-h-[80px] rounded-md">
                <div className="absolute left-2 top-1/2 -translate-y-1/2 flex items-center gap-2">
                    {GateAccessIcon}
                    <GateSymbol />
                </div>
                
                <div className="flex flex-col items-center justify-center text-center w-full px-20">
                    <span className="text-lg text-foreground font-semibold">{name}</span>
                    {patrolPoints.length > 0 && (
                        <div className="flex justify-around w-full mt-2">
                            {patrolPoints.map((p, index) => (
                               <PatrolPoint key={index} label={p.label} status={p.status} onClick={() => onPatrolPointClick(index)} />
                            ))}
                        </div>
                    )}
                </div>

                <div className="absolute right-2 top-1/2 -translate-y-1/2 flex items-center gap-2">
                    <GateSymbol />
                    {GateAccessIcon}
                </div>
            </div>
        </div>
    );
}

export default function DiagramPage() {
    const [tracks, setTracks] = useState<TrackState[]>(initialTracks);
    const [currentUser] = useState<User>(initialUser);
    
    const isOperator = currentUser.role.name === '操作员';

    const handleIsolatorToggle = (trackId: string) => {
        if (isOperator) {
            alert("无操作权限：仅管理员可操作隔离开关。");
            return;
        }
        setTracks(prevTracks => prevTracks.map(track => {
            if (track.id !== trackId) return track;
            const newTrack = { ...track };
            
            const wantsToClose = !newTrack.isolatorClosed;
            if (wantsToClose && newTrack.groundingRod.status === 'done') {
                alert('危险操作：线路已接地，禁止合闸！');
                return track;
            }
    
            newTrack.isolatorClosed = !newTrack.isolatorClosed;
            if(newTrack.isolatorClosed && newTrack.groundingRod.status !== 'done') newTrack.status = 'energized';
            if(!newTrack.isolatorClosed) newTrack.status = 'de-energized';
            
            newTrack.gateAccess = 'denied';
            return newTrack;
        }));
    };

    const handleActionItemToggle = (trackId: string, itemType: 'verificationPoint' | 'groundingRod' | 'patrolPoint', index?: number) => {
        if (isOperator) {
            alert("无操作权限：仅管理员可执行此操作。");
            return;
        }
        setTracks(prevTracks => prevTracks.map(t => {
            if (t.id !== trackId) return t;
    
            const track = JSON.parse(JSON.stringify(t));
    
            const toggleStatus = (item: ActionableItem) => {
                 item.status = item.status === 'done' ? 'not_done' : 'done';
            };
    
            if (itemType === 'groundingRod') {
                const wantsToGround = track.groundingRod.status === 'not_done';
                if (wantsToGround && (track.isolatorClosed || track.status === 'energized')) {
                    alert('危险操作：线路带电或隔离开关未拉开，禁止接地！');
                    return t;
                }
                toggleStatus(track.groundingRod);
                track.gateAccess = track.groundingRod.status === 'done' ? 'allowed' : 'denied';
            } 
            else if (itemType === 'verificationPoint') {
                toggleStatus(track.verificationPoint);
            }
            else if (itemType === 'patrolPoint' && index !== undefined) {
                if(track.gateAccess !== 'allowed') {
                    alert('门禁未授权，无法操作巡检点！');
                    return t;
                }
                toggleStatus(track.patrolPoints[index]);
            }
            return track;
        }));
    };

    const getStatusIcon = (status: Status) => {
      switch (status) {
        case 'energized': return <AlertTriangle className="h-4 w-4 text-[#FF4D4F]" />;
        case 'de-energized': return <CheckCircle className="h-4 w-4 text-[#52C41A]" />;
      }
    };

  return (
    <div className="space-y-6 bg-muted/30 p-4 md:p-6 rounded-lg">
      <div>
        <h1 className="text-2xl font-bold tracking-tight mb-2">联合检修库</h1>
        <p className="text-muted-foreground">
          常州轨道交通2号线丁堰车辆段检修平台供电示意图
        </p>
      </div>

      <div className="space-y-6">
          {isOperator && (
            <div className="flex items-center justify-center gap-2 rounded-lg border border-yellow-400/30 bg-yellow-500/10 p-3 text-yellow-600">
              <ShieldAlert className="h-5 w-5" />
              <p>您当前以 <span className="font-bold">操作员</span> 身份登录，仅可查看，无法进行操作。</p>
            </div>
          )}

          {tracks.map((track, index) => (
            <Card key={track.id} className="overflow-hidden shadow-sm hover:shadow-md transition-shadow">
              <CardContent className="p-4">
                <div className="flex">
                  <div className="flex flex-col justify-around items-center py-4 pr-4 border-r border-border w-[100px]">
                    <StatusIndicator label="有电" active={track.status === 'energized'} color="red" />
                    <StatusIndicator label="无电" active={track.status === 'de-energized'} color="green" />
                  </div>

                  <div className="flex-1 flex flex-col justify-center px-4">
                    <div className="flex justify-start items-end h-12">
                      <IsolatorSwitch name={track.name} closed={track.isolatorClosed} onClick={() => handleIsolatorToggle(track.id)} />
                    </div>
                    <TrackLine />
                    <div className="flex justify-start items-start h-14 space-x-4 pl-16">
                      <VerificationPoint status={track.verificationPoint.status} onClick={() => handleActionItemToggle(track.id, 'verificationPoint')} />
                      {track.groundingRod.label && <GroundingRod label={track.groundingRod.label} status={track.groundingRod.status} onClick={() => handleActionItemToggle(track.id, 'groundingRod')} />}
                    </div>
                  </div>
                  <div className="flex items-center pl-4 gap-2">
                    <TrackIdLabel id={track.id} />
                    <StatusBadge status={
                      track.status === 'energized' ? 'error' : 'normal'
                    } className="flex items-center gap-1 min-w-[80px] justify-center">
                      {getStatusIcon(track.status)}
                      {track.status === 'energized' ? '带电' : '断电'}
                    </StatusBadge>
                  </div>
                </div>

                <div className="mt-4 pl-[124px] flex flex-col space-y-2">
                  {track.platformNames.map((name, pIndex) => {
                    const platformPatrolPoints = track.patrolPoints.length > track.platformNames.length
                      ? track.patrolPoints
                      : (track.patrolPoints[pIndex] ? [track.patrolPoints[pIndex]] : []);
                    
                    return (
                      <PlatformDisplay 
                        key={pIndex} 
                        name={name} 
                        gateAccess={track.gateAccess}
                        patrolPoints={platformPatrolPoints}
                        onPatrolPointClick={(_patrolIndexInComponent) => {
                          const originalPatrolPointIndex = track.patrolPoints.length > track.platformNames.length
                            ? _patrolIndexInComponent
                            : pIndex;
                          handleActionItemToggle(track.id, 'patrolPoint', originalPatrolPointIndex)
                        }}
                      />
                    )
                  })}
                </div>
              </CardContent>
            </Card>
          ))}
      </div>
    </div>
  );
}
